<template>
  <div class="container">
    <div ref="main" class="mychart" :class="guoClass"></div>
    <div class="shengChart" :class="shengClass">
      <EchartMapSheng :shengSeriesNameProp="this.dataShengMap.shengMapName" :shengSeriesMapProp="this.dataShengMap.shengSeriesMap" :shengBaseMapProp="dataShengBaseMap" :shengSeriesMapZoomProp="shengZoom" :shengSeriesDataProp="this.dataShengMap.shengMapData" :shengVisualMapProp="{}" :shengSpecialAreasProp="{}" :shengShowVisualMap="false" :shengMapBgColorProp="shengMapBgColorProp" :shengMapBgEmColorProp="shengMapBgEmColorProp" :showCities="this.dataShengMap.showCities"></EchartMapSheng>
      <div class="hideSheng" @click="hideShengMap"></div>
    </div>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import { requestHFCity } from '@/api/request.js'
import { mapMutations } from "vuex";
import { request } from '@/api/request.js'
import axios from 'axios'
import EchartMapSheng from "@/components/EchartMapSheng.vue"
export default {
  name: 'EchartMap',
  props: {
    titleProp: {
      type: Object,
      default: () => ({}),
      required: false
    },
    visualMapProp: {
      type: Object,
      default: () => ({}),
      required: false
    },
    specialAreasProp: {
      type: Object,
      default: () => ({}),
      required: false
    },
    seriesNameProp: {
      type: String,
      default: () => 'USA PopEstimates',
      required: false
    },
    seriesMapProp: {
      type: String,
      default: () => 'USA',
      required: false
    },
    seriesMapZoomProp: {
      type: Number,
      default: () => 1,
      required: false
    },
    seriesMapTopProp: {
      type: String,
      default: () => '50%',
      required: false
    },
    baseMapProp: {
      type: Object,
      default: () => {},
      required: false
    },
    seriesDataProp: {
      type: Array,
      default: () => [],
      required: false
    },
    mapUrlProp: {
      type: String,
      default: () => '',
      required: false
    },
    showVisualMap: {
      type: Boolean,
      default: () => false,
      required: false
    },
    mapBgColorProp: {
      type: String,
      default: () => 'rgba(0,0,0,0)',
      required: false
    },
    mapBgEmColorProp: {
      type: String,
      default: () => 'rgba(0,0,0,0)',
      required: false
    },
    showProvinces: {
      type: Array,
      default: () => [],
      required: false
    }
  },
  data() {
    return {
      guoClass:"",
      shengClass:"hidden",
      hefengKey: 'a981619d96b54e83a1425eff4e342267',
      shengMapBgColorProp: "#192f5a",
      shengMapBgEmColorProp: "#0ee3f6",
      myChart: {},
      option: {
        title: this.titleProp,
        animationDuration: 0,
        geo: {
          map: this.seriesMapProp,
          roam: false,
          show: true,
          itemStyle: {
            areaColor: this.mapBgColorProp,
            borderWidth: 1,
            borderColor: 'rgba(34,93,165,1)'
          },
          silent: true,//禁用地图hover事件
          tooltip: {
            show: false
          },
          emphasis:{
            itemStyle: {
              areaColor: this.mapBgEmColorProp,
              borderWidth: 1,
              borderColor: 'rgba(34,93,165,1)'
            }
          },
          regions: [
            {
              name: this.$store.state.highlightCityNameNow,
              itemStyle: {
                normal:{
                  areaColor: this.mapBgEmColorProp,
                  borderWidth: 1,
                  borderColor: 'rgba(34,93,165,1)'
                }
              }
            }
          ],
          zlevel: 3
        },
        tooltip: {
          trigger: 'item',
          showDelay: 0,
          transitionDuration: 0.2
        },
        // visualMap: this.visualMapProp,
        toolbox: {
          show: false,
          //orient: 'vertical',
          left: 'left',
          top: 'top',
          feature: {
            dataView: { readOnly: false },
            restore: {},
            saveAsImage: {}
          }
        },
        series: [
          {
            name: this.seriesNameProp,
            type: 'map',
            roam: false,
            map: this.seriesMapProp,
            zoom: this.seriesMapZoomProp,
            // top: this.seriesMapTopProp,
            silent: true,//禁用地图hover事件
            // selectedMode: false,//禁用地图点击事件
            emphasis: {
              label: {
                show: false
              },
              tooltip: {
                show: false
              }
            },
            z: 2,
            zlevel: 2,
            data: this.seriesDataProp,
            animationDuration: 0
          },
          // this.randomPieSeries([118.187759, 36.376092], 12),
        ]
      },
      centers:[],
      centersData:[],
      highlightScatterOld: 0,
      highlightScatterNow: 1,
      highlightCityNameOld: '',
      highlightCityNameNow: this.$store.state.highlightCityNameNow,
      dataShengBaseMap:{},
      dataShengMap:{},
      shengName:"hainan",
      shengBaseMapJSON:'./json/shengjson/hainan.json',
      shengZoom: 1
    }
  },
  mounted() {
    this.getShengBaseMap();
    this.getShengMap();
    // this.highlightCityNameNow = this.$store.state.highlightCityNameNow;
    this.initChart();
    this.myChart.on('georoam', (params) => {
      let myOption = this.myChart.getOption();
      if (params.zoom != null && params.zoom != undefined) { //捕捉到缩放时
        myOption.series[0].zoom = myOption.geo[0].zoom;//myChart的缩放等级跟着上层的geo一起改变
        myOption.series[0].center = myOption.geo[0].center;//myChart的中心位置随着上层geo一起改变
      } else {//捕捉到拖曳时
        myOption.series[0].center = myOption.geo[0].center;//myChart的中心位置随着上层geo一起改变
      }
      this.myChart.setOption(myOption);//设置option
    });
    this.myChart.on('click',(params)=>{
      if (params.componentSubType=='scatter') {
        // 必须通过setProIdStore修改store中的provinceId，才能改变页面上的数据显示
        this.setProIdStore(params.value[4]);
        this.setHighlightCityNameStore(params.value[2]);
        this.highlightScatterOld = this.highlightScatterNow;
        this.highlightScatterNow = params.dataIndex;
        this.myChart.dispatchAction({
          type:'downplay',
          dataIndex:this.highlightScatterOld
        });
        this.myChart.dispatchAction({
          type:'highlight',
          dataIndex:this.highlightScatterNow
        });
        let myOption = this.myChart.getOption();
        // myOption.geo[0].regions.forEach((ele)=>{
        //   if (ele.name==this.$store.state.highlightCityNameNow) {
        //     this.option.geo.regions[0].name = this.$store.state.highlightCityNameNow;
        //   }
        // });
        let HLSheng = myOption.geo[0].regions.filter(item=>item.name==this.$store.state.highlightCityNameNow)
        myOption.geo[0].regions.forEach((ele)=>{
          if (ele.name==this.$store.state.highlightCityNameNow) {
            this.option.geo.regions[0].name = this.$store.state.highlightCityNameNow;
          }
        });
            // console.log("和风天气接口获取城市id",this.$store.state.proCityIdName);
        if (this.$store.state.morethan1Shengs.indexOf(HLSheng[0].name)!=-1) {
          this.shengClass = "";
          this.guoClass = "transele";
          this.queryShengName(HLSheng[0].name);
          this.getShengMap();
          let thisCity = this.dataShengBaseMap.features.filter(item=>item.properties.name==this.dataShengMap.showCities[0]);
          if (this.$store.state.proCityId == '') {
            this.setProIdStore(thisCity[0].properties.adcode);
            this.sethighlightShengCityNameStore(thisCity[0].properties.name);
            // 调用和风天气接口获取城市id
            this.getCityNo(thisCity[0].properties.name);
          }else{
            this.setProIdStore(this.$store.state.proCityId);
            this.sethighlightShengCityNameStore(this.$store.state.proCityIdName);
          console.log("proCityIdName",this.$store.state.proCityIdName);
            // 调用和风天气接口获取城市id
            this.getCityNo(this.$store.state.proCityIdName);
          }
        }else{
          // 调用和风天气接口获取城市id
          this.getCityNo(params.value[2]);
        }
      }else{
        console.log(params.name);
        
      }
    });
  },
  methods: {
    ...mapMutations(['setProIdStore','setHighlightCityNameStore','setHFCityNoStore',"sethighlightShengCityNameStore"]),
    initChart() {
      this.myChart = echarts.init(this.$refs.main,null,{renderer:'svg'});
      if (this.showVisualMap==true) {
        this.option.visualMap = this.visualMapProp;
      }
      echarts.registerMap(this.seriesMapProp, this.baseMapProp, this.specialAreasProp);
      this.myChart.setOption(this.option);
      this.myChart.dispatchAction({
        type:'highlight',
        dataIndex:this.highlightScatterNow
      })
    },
    genScatters(sdata){
      let mapZoom = parseFloat(this.$store.state.htmlScale);
      let baseFontSize = 12;
      let labelFontSize = baseFontSize*mapZoom;
      let shengData = [];
      let centersData = [
        [0,0,'',0]
      ];
      sdata.forEach((item,index) => {
        if (this.showProvinces.indexOf(item.properties.name)!=-1) {
          // centersData.push(item.properties.centroid,)
          centersData.push([item.properties.centroid[0],item.properties.centroid[1],this.seriesDataProp[index].name,this.seriesDataProp[index].value,item.properties.adcode,this.getCity(this.seriesDataProp[index].name)])
        }
      });
      this.seriesDataProp.forEach(item => {
        if (this.showProvinces.indexOf(item.name)!=-1) {
          shengData.push([item.name, item.value])
        }
      });
      this.option.series.push({
        type: 'scatter',
        coordinateSystem: 'geo',
        symbolSize: function (params) {
          return Math.sqrt(params[3])/500>10 ? (Math.sqrt(params[3])/500)*mapZoom : 10*mapZoom;
        },
        color: '#ffff00',
        tooltip: {
          formatter: function (params) {
            return params.data[2]+'：'+params.data[3];
          }
        },
        label: {
          show: true,
          color: '#ffffff',
          fontSize:labelFontSize,
          fontWeight: 'bold',
          position: 'right',
          formatter: function (params) {
            return params.data[5];
          }
        },
        emphasis:{
          itemStyle:{
            color: '#f89b06',
          },
          label:{
            color: '#ffff00',
          }
        },
        labelLine: {
          show: false
        },
        animationDuration: 0,
        z: 6,
        zlevel: 6,
        data: centersData
      });
    },
    randomPieSeries(center, radius) {
      let data = []
      data.push(center);
      return {
        type: 'scatter',
        coordinateSystem: 'geo',
        symbolSize: radius,
        color: '#ffff00',
        tooltip: {
          formatter: '{b}: {c} ({d}%)'
        },
        label: {
          show: true,
          position: 'right'
        },
        labelLine: {
          show: false
        },
        animationDuration: 0,
        z: 6,
        zlevel: 6,
        // radius: radius,
        // center: center,
        data: data
      };
    },
    getCity(province){
      let cityName = '';
      if (province=='山东省') {
        cityName = '山东';
      }else if(province=='云南省'){
        // cityName = '西双版纳';
        cityName = '云南';
      }else if(province=='海南省'){
        cityName = '海南';
      }else if(province=='广西'){
        cityName = '广西';
      }else{
        cityName = province
      }
      return cityName
    },
    getCityNo(province) {
      let cityName = this.getCity(province)
      requestHFCity({
        url: '/city/lookup?location='+cityName+'&key='+this.hefengKey,
        method: 'get'
      }).then(res => {
        this.setHFCityNoStore(res.data.location[0].id);
      });
    },
    hideShengMap(){
      this.shengClass = "hidden";
      this.guoClass = "";
    },
    getShengBaseMap(){
      // 获取本地json文件中的数据
      // 在vue3中 需要把json文件放置在 public 文件夹下，必须用‘./’路径获取json文件
      axios.get(this.shengBaseMapJSON).then(res=>{
        this.dataShengBaseMap = res.data;
      })
    },
    getShengMap(){
      // 获取本地json文件中的数据
      // 在vue3中 需要把json文件放置在 public 文件夹下，必须用‘./’路径获取json文件
      request({
        url: '/shengMapDatas',
        method: 'get'
      }).then(res=>{
        this.dataShengMap = res.data[this.shengName];
      })
    },
    queryShengName(sheng){
      let name = ""
      if (sheng=='海南省') {
        name = "hainan"
      }else if (sheng=='山东省') {
        name = "shandong"
      }
      this.shengName = name;
    }
  },
  computed:{
    // shengBaseMapJSON(){
    //   return './json/china_'+this.shengName+'.json'
    // }
  },
  components:{
    EchartMapSheng
  },
  watch: {
    seriesDataProp: {
      handler() {
        this.$nextTick(() => {
          this.initChart()
        })
      },
      deep: true,
      immediate: true
    },
    baseMapProp: {
      handler(newVal) {
        this.$nextTick(() => {
          this.initChart();
          this.genScatters(newVal.features)
        })
      },
      deep: true,
      immediate: false
    },
    option: {
      handler() {
        // this.option1.series[0].data = newVal
        // this.wsData = newVal
        this.$nextTick(() => {
          this.initChart()
        })
      },
      deep: true,
      immediate: true
    },
    '$store.state': {
      deep: true,
      immediate: false,
      handler() {
        this.$nextTick(()=>{
          if (this.$store.state.colors) {
            this.option.geo.itemStyle.areaColor = this.$store.state.colors.mapBgColor;
            this.option.geo.emphasis.itemStyle.areaColor = this.$store.state.colors.mapBgEmColor;
            this.option.geo.itemStyle.borderColor = this.$store.state.colors.mapBorderColor;
            this.option.series[1].label.color = this.$store.state.colors.mapScatterTextColor;
            this.option.series[1].emphasis.itemStyle.color = this.$store.state.colors.mapScatterEmColor;
            this.option.series[1].emphasis.label.color = this.$store.state.colors.mapScatterEmTextColor;
          }
          
          this.option.geo.regions.name = this.$store.state.highlightCityNameNow;
          this.initChart();
        })
      }
    },
  },
}
</script>
<style lang="less" scoped>
.container{
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  .mychart {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 2;
  }
  .shengChart{
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: transparent;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 6;
    .hideSheng{
      width: 4rem;
      height: 4rem;
      background-color: red;
      position: absolute;
      right: 0.2rem;
      top: 0.2rem;
      z-index: 8;
    }
  }
  .hidden{
    display: none;
  }
  .transele{
    opacity: 0;
  }
}
</style>